<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin:20px">
      <template #header>
        <el-form ref="form" label-width="80px" :inline="true" size="normal">
          <el-form-item label="">
            <el-input v-model="username"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button @click="clearSearch">清空</el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" size="default" @click="addUser">添加</el-button>
          <el-button type="danger" size="default" @click="removeUsers" :disabled="!selectedIds.length">批量删除</el-button>
        </div>

      </template>
      <el-table :data="userList" @selection-change="handleSelectionChange" border stripe>

        <el-table-column type="selection" width="55" />

        <el-table-column type="index" label="序号" width="80" align="center" />

        <el-table-column prop="username" label="用户名" width="150" v-model="userInfo.username" />
        <el-table-column prop="nickName" label="用户昵称" />
        <el-table-column prop="roleName" label="角色列表" width="200" />

        <el-table-column prop="gmtCreate" label="创建时间" width="180" />
        <el-table-column prop="gmtModified" label="更新时间" width="180" />

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template v-slot="{ row }">
            <el-button type="info" size="small" icon="el-icon-user-solid" title="分配角色" @click="getRoleList(row)" />
            <el-button type="primary" size="small" icon="el-icon-edit" title="修改用户" @click="UpdateUser(row)" />
            <el-popconfirm @onConfirm="removeUser(row.id)" :title="`确定删除 ${row.username} 吗?`">
              <template #reference>
                <span>
                  <el-button style="margin-left:10px" type="danger" size="small" icon="el-icon-delete" title="删除用户2"
                    v-has="btn.User.remove" />
                </span>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="sizeChange" @current-change="currentChange" :currentPage="currentPage"
        :page-sizes="[3, 6, 9, 12]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum" background :pager-count="7">
      </el-pagination>


    </el-card>

    <!-- 添加和修改的弹窗 -->
    <el-dialog :title="userInfo.id ? '修改用户' : '添加用户'" :visible.sync="isShowAddDia" width="40%">
      <el-form label-width="120px" :inline="false" size="default" :model="userInfo" :rules="userRules" ref="ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="userInfo.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="isShowAddDia = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色的弹窗 -->
    <el-dialog title="设置角色" :visible.sync="isShowRoleDia" width="50%">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
            @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="assignRolesId" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="role in allRolesList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>



      <template #footer>
        <span>
          <el-button @click="isShowRoleDia = false">取消</el-button>
          <el-button type="primary" @click="assignRole">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script >
import { reqUserList, reqAddUser, reqUpdate, reqRemoveUser, reqRoleList, reqAssignRole, reqRemoveUsers } from '@/api/acl/user'
export default ({
  name: "user",

  data() {
    return {
      currentPage: 1,//当前页
      pageSize: 3,//每页数量
      totalNum: 20,//数据总条数
      userList: [],//用户列表
      username: '',//用户名
      searchUsername: '',//搜索用户名
      isShowAddDia: false,//添加和修改用户的弹窗
      userInfo: {
        id: '',
        username: '',//用户名
        nickName: '',//用户昵称
        password: '',//用户密码
      },
      // 添加用户的表单单独验证
      userRules: {
        username: [
          { required: true, message: '用户名必须输入' },
          { min: 4, message: '用户名不能小于4位' }
        ],
        password: [
          { required: true, validator: this.validatePassword }
          // { required: true, message: '密码必须输入' },
          // { min: 6, message: '密码不能小于6位' }
        ]
      },
      isShowRoleDia: false,//分配角色的弹窗
      allRolesList: [],//所有已有角色
      assignRoles: [],//该用户已经设置的角色
      assignRolesId: [],//该用户已经设置的角色的id
      isIndeterminate: true,//
      checkAll: false,//角色是否全选
      selectedIds: [],//被选中用户的id
    }
  },
  mounted() {
    this.getUserList()
  },

  methods: {
    // 每页数量改变
    sizeChange(val) {
      // console.log(val, 'sizeChange');
      this.pageSize = val,
        this.getUserList()
    },
    // 当前页改变
    currentChange(val) {
      // console.log(val, 'currentChange');
      this.currentPage = val
      this.getUserList()
    },

    // 获取用户列表
    async getUserList() {
      try {
        let res = await reqUserList(this.currentPage, this.pageSize, { username: this.searchUsername })
        // console.log(res, 'res');
        this.totalNum = res.data.total
        this.userList = res.data.items
      } catch (error) {
        this.$message.error(error, '获取用户列表失败')
      }
    },
    // 查询用户
    search() {
      this.searchUsername = this.username
      this.getUserList()
    },
    // 清空
    clearSearch() {
      this.searchUsername = ''
      this.username = ''
      this.getUserList()
    },

    // 添加或修改用户
    addOrUpdateUser() {
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          try {
            if (this.userInfo.id) {
              await reqUpdate(this.userInfo)
              this.$message.success('修改用户成功')
            } else {
              await reqAddUser(this.userInfo)
              this.$message.success('添加用户成功')
            }

            this.getUserList()
            this.isShowAddDia = false
          } catch (error) {
            this.$message.error(error, '添加用户失败')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 自定义表单验证规则
    validatePassword(rule, value, callback) {
      if (!value) {
        callback('密码必须输入')
      } else if (!value || value.length < 6) {
        callback('密码不能小于6位')
      } else {
        callback()
      }
    },

    // 新增用户，清空表单
    addUser() {
      this.isShowAddDia = true
      this.userInfo = {
        id: '',
        username: '',//用户名
        nickName: '',//用户昵称
        password: '',//用户密码
      }
    },
    // 修改用户，回填数据
    UpdateUser(row) {
      this.userInfo = row
      this.isShowAddDia = true
    },

    // 删除某个用户
    async removeUser(id) {
      await reqRemoveUser(id)
      // console.log(1111);
      this.getUserList()
    },

    // 获取角色列表
    async getRoleList(row) {
      this.isShowRoleDia = true
      this.userInfo = row

      try {
        let res = await reqRoleList(row.id)
        // console.log(res, 'reqRoleList');
        this.allRolesList = res.data.allRolesList
        this.assignRoles = res.data.assignRoles
        this.assignRolesId = this.assignRoles.map(item => item.id)
        // console.log( this.assignRolesId,' this.assignRolesId');
        // console.log( this.allRolesList, 'this.allRolesList');
      } catch (error) {
        this.$message.error(error, '获取角色列表失败')
      }
    },

    // 角色弹窗中的事件
    //   全选勾选状态发生改变的监听
    handleCheckAllChange(val) {
      this.assignRoles = val ? this.allRolesList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    // 角色列表选中项发生改变的监听(角色全部选中全选)
    handleCheckedCitiesChange() {
      this.checkAll = this.assignRoles.length === this.allRolesList.length && this.allRolesList.length > 0;
      this.isIndeterminate = this.assignRoles.length > 0 && this.assignRoles.length < this.allRolesList.length;
    },

    // 用户角色授权
    async assignRole() {
      const userId = this.userInfo.id
      const roleIds = this.assignRolesId.join(',')
      await reqAssignRole(userId, roleIds)
      this.$message.success('用户角色授权成功');
      this.isShowRoleDia = false
      this.getUserList()
    },

    // 列表选中状态发生改变的监听回调(用来获取批量删除用户需要的ids)
    handleSelectionChange(selection) {
      // console.log(selection, 'selection');
      this.selectedIds = selection.map(item => item.id)
      // console.log( this.selectedIds,' this.selectedIds');
    },
    // 批量删除用户
    async removeUsers() {
      try {
        await reqRemoveUsers(this.selectedIds)
        this.getUserList()
      } catch (error) {
        this.$message.error(error, '批量删除用户失败')
      }
    }

  },

});
</script>

<style  scoped lang="scss">

</style>